const express = require("express");
const router = express.Router();
const multerConfig = require('../multerConfig')
const config = require("../config");

// 上传到服务器的目录
const imgPath = '/img/'

// 封装上传图片的接口
function uploadAvatar(req, res) {
    return new Promise((resolve, reject) => {
        multerConfig.single('file')(req, res, function (err) {
            if (err) {
                // 传递的图片格式错误或者超出文件限制大小，就会reject出去
                reject(err)
            } else {
                //动态获取服务器地址
                resolve(config.imgBaseUrl + imgPath + req.file.filename)
            }
        })
    })
}


router.post("/upload", async (req, res) => {
    try {
        const uploadRes = await uploadAvatar(req, res);
        res.output("上传成功", 0, uploadRes);
    } catch (error) {
        res.output(error, 500, null);
    }
});

module.exports = router;
